<template>
  <div class="registration-order-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>挂号订单管理 {{ loading ? '...' : '' }}</h2>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <h3>筛选 {{ loading ? '...' : '' }}</h3>
      <div class="filter-form">
        <div class="filter-item">
          <label>输入订单号或用户名：</label>
          <input 
            v-model="searchFilter.orderNoOrUsername" 
            type="text" 
            placeholder="请输入订单号或用户名"
            class="filter-input"
            @input="debouncedSearch"
            :disabled="loading"
          />
        </div>
        <div class="filter-item">
          <label>开始时间：</label>
          <input 
            v-model="searchFilter.startTime" 
            type="datetime-local" 
            class="filter-input"
            :disabled="loading"
          />
        </div>
        <div class="filter-item">
          <label>结束时间：</label>
          <input 
            v-model="searchFilter.endTime" 
            type="datetime-local" 
            class="filter-input"
            :disabled="loading"
          />
        </div>
        <button @click="applyFilter" class="filter-button" :disabled="loading">
          {{ loading ? '...' : '筛选' }}
        </button>
        <button @click="resetFilter" class="reset-button" :disabled="loading">
          {{ loading ? '...' : '重置' }}
        </button>
        <button @click="loadOrderData" class="refresh-button" :disabled="loading">
          {{ loading ? '...' : '刷新' }}
        </button>
      </div>
    </div>

    <!-- 数据列表区域 -->
    <div class="data-list-section">
      <h3>数据列表 {{ loading ? '...' : '' }}</h3>
      
      <!-- 状态标签页 -->
      <div class="status-tabs">
        <button 
          v-for="tab in statusTabs" 
          :key="tab.key"
          @click="switchStatus(tab.key)"
          :class="['status-tab', { active: currentStatus === tab.key }]"
          :disabled="loading"
        >
          {{ tab.label }} {{ loading && currentStatus === tab.key ? '...' : '' }}
        </button>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <p class="error-message">{{ error }}</p>
        <button @click="loadOrderData" class="retry-button">重试</button>
      </div>

      <!-- 数据表格 -->
      <div v-else-if="!error" class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>订单编号</th>
              <th>提交时间</th>
              <th>用户名</th>
              <th>医生</th>
              <th>科室</th>
              <th>挂号费</th>
              <th>订单状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="order in orderData" :key="order.id" class="table-row">
              <td>{{ order.orderNo }}</td>
              <td>{{ formatDateTime(order.createdAt) }}</td>
              <td>{{ order.username || '未知' }}</td>
              <td>{{ order.doctorName || '未知' }}</td>
              <td>{{ order.departmentName || '未知' }}</td>
              <td>¥{{ order.fee }}</td>
              <td>
                <span :class="['status-badge', getStatusClass(order.status)]">
                  {{ getStatusText(order.status) }}
                </span>
              </td>
              <td>
                <div class="action-buttons">
                  <button 
                    @click="viewOrderDetail(order.id)" 
                    class="action-button view-button"
                    :disabled="loading"
                  >
                    {{ loading ? '...' : '查看订单' }}
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        
        <!-- 空数据提示 -->
        <div v-if="orderData.length === 0 && !loading && !error" class="empty-data">
          <p>暂无数据</p>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="totalPages > 1 && !loading" class="pagination">
      <button 
        @click="changePage(currentPage - 1)" 
        :disabled="currentPage === 1 || loading"
        class="page-button prev-button"
      >
        {{ loading ? '...' : '&lt;' }}
      </button>
      <div class="page-numbers">
        <button 
          v-for="page in visiblePages" 
          :key="page"
          @click="changePage(page)"
          :class="['page-number', { active: currentPage === page }]"
          :disabled="loading"
        >
          {{ loading && currentPage === page ? '...' : page }}
        </button>
      </div>
      <button 
        @click="changePage(currentPage + 1)" 
        :disabled="currentPage === totalPages || loading"
        class="page-button next-button"
      >
        {{ loading ? '...' : '&gt;' }}
      </button>
      <span class="page-info">
        {{ loading ? '...' : `共${totalPages}页/${totalCount}条数据` }}
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import api from '../utils/request';

// 防抖函数
const debounce = (func: Function, delay: number) => {
  let timeoutId: number;
  return (...args: any[]) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(null, args), delay);
  };
};

const router = useRouter();
const route = useRoute();

// 响应式数据
const loading = ref(false);
const error = ref<string | null>(null);
const orderData = ref<any[]>([]);
const totalCount = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索筛选条件
const searchFilter = reactive({
  orderNoOrUsername: '',
  startTime: '',
  endTime: ''
});

// 当前状态
const currentStatus = ref('all');

// 状态筛选选项
const statusTabs = [
  { key: 'all', label: '全部' },
  { key: '0', label: '待支付' },
  { key: '1', label: '已完成' },
  { key: '2', label: '已取消' },
  { key: '3', label: '已退款' }
];

// 计算属性
const totalPages = computed(() => {
  return Math.ceil(totalCount.value / pageSize.value);
});

const visiblePages = computed(() => {
  const pages = [];
  const maxVisible = 10;
  let start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2));
  let end = Math.min(totalPages.value, start + maxVisible - 1);
  
  if (end - start + 1 < maxVisible) {
    start = Math.max(1, end - maxVisible + 1);
  }
  
  for (let i = start; i <= end; i++) {
    pages.push(i);
  }
  return pages;
});

// 方法
const loadOrderData = async () => {
  try {
    loading.value = true;
    
    // 构建查询参数
    const params: any = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value
    };

    // 添加搜索条件
    if (searchFilter.orderNoOrUsername) {
      params.orderNoOrUsername = searchFilter.orderNoOrUsername;
    }

    if (searchFilter.startTime) {
      params.startTime = searchFilter.startTime;
    }

    if (searchFilter.endTime) {
      params.endTime = searchFilter.endTime;
    }

    // 添加状态筛选
    if (currentStatus.value !== 'all') {
      params.status = parseInt(currentStatus.value);
    }

    const response = await api.registrationOrder.getPagedList(params);
    
    if (response && response.data) {
      orderData.value = response.data.items || [];
      totalCount.value = response.data.totalCount || 0;
      // 更新当前页码信息
      currentPage.value = response.data.currentPage || 1;
      // 清除错误状态
      error.value = null;
    }
  } catch (err) {
    console.error('获取挂号订单列表失败:', err);
    // 显示更友好的错误信息
    const errorMessage = err instanceof Error ? err.message : '获取挂号订单列表失败，请重试';
    error.value = errorMessage;
    // 清空数据
    orderData.value = [];
    totalCount.value = 0;
  } finally {
    loading.value = false;
  }
};

// 防抖的搜索函数
const debouncedSearch = debounce(() => {
  currentPage.value = 1;
  loadOrderData();
}, 500);

const applyFilter = () => {
  // 验证时间范围
  if (searchFilter.startTime && searchFilter.endTime) {
    const startTime = new Date(searchFilter.startTime);
    const endTime = new Date(searchFilter.endTime);
    if (startTime > endTime) {
      alert('开始时间不能晚于结束时间');
      return;
    }
  }
  
  currentPage.value = 1;
  loadOrderData();
};

const resetFilter = () => {
  searchFilter.orderNoOrUsername = '';
  searchFilter.startTime = '';
  searchFilter.endTime = '';
  currentStatus.value = 'all';
  currentPage.value = 1;
  error.value = null; // 清除错误状态
  loadOrderData();
};

const switchStatus = (status: string) => {
  currentStatus.value = status;
  currentPage.value = 1;
  loadOrderData();
};

const getStatusClass = (status: number) => {
  const statusClasses = {
    0: 'status-pending',
    1: 'status-completed',
    2: 'status-cancelled',
    3: 'status-refunded',
    4: 'status-refunded' // 根据API文档，状态4也是已退款
  };
  return statusClasses[status as keyof typeof statusClasses] || 'status-unknown';
};

const getStatusText = (status: number) => {
  const statusTexts = {
    0: '待支付',
    1: '已完成',
    2: '已取消',
    3: '已退款',
    4: '已退款' // 根据API文档，状态4也是已退款
  };
  return statusTexts[status as keyof typeof statusTexts] || '未知状态';
};

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

const viewOrderDetail = (orderId: number) => {
  router.push(`/registration-order-detail/${orderId}`);
};

const changePage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
    loadOrderData();
  }
};

// 监听搜索条件变化，自动搜索
watch(() => searchFilter.orderNoOrUsername, () => {
  debouncedSearch();
});

// 监听路由参数变化，处理刷新和状态筛选
watch(() => route.query, (newQuery) => {
  if (newQuery.refresh === 'true') {
    loadOrderData();
    // 清除刷新参数
    router.replace({ query: {} });
  } else if (newQuery.status) {
    // 处理状态筛选参数
    currentStatus.value = newQuery.status as string;
    currentPage.value = 1;
    loadOrderData();
  }
}, { immediate: true });

onMounted(() => {
  loadOrderData();
});
</script>

<style scoped>
.registration-order-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #333;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

/* 筛选区域 */
.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.filter-section h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.filter-form {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.filter-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 200px;
}

.filter-input:focus {
  outline: none;
  border-color: #409eff;
}

.filter-input:disabled {
  background-color: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

.filter-button {
  padding: 8px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.filter-button:hover {
  background-color: #337ecc;
}

.filter-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.filter-button:disabled:hover {
  background-color: #ccc;
}

.reset-button {
  padding: 8px 20px;
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.reset-button:hover {
  background-color: #e6e6e6;
  border-color: #ccc;
}

.reset-button:disabled {
  background-color: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

.reset-button:disabled:hover {
  background-color: #f5f5f5;
  border-color: #ddd;
}

.refresh-button {
  padding: 8px 20px;
  background-color: #67c23a;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.refresh-button:hover {
  background-color: #5daf34;
}

.refresh-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.refresh-button:disabled:hover {
  background-color: #ccc;
}

/* 数据列表区域 */
.data-list-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-list-section h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

/* 状态标签页 */
.status-tabs {
  display: flex;
  gap: 0;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.status-tab {
  padding: 12px 24px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.status-tab:hover {
  color: #409eff;
}

.status-tab.active {
  color: #409eff;
  border-bottom-color: #409eff;
}

.status-tab:disabled {
  color: #ccc;
  cursor: not-allowed;
}

.status-tab:disabled:hover {
  color: #ccc;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 错误状态 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px;
  color: #f56c6c;
}

.error-message {
  margin-bottom: 15px;
  font-size: 14px;
}

.retry-button {
  padding: 8px 20px;
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.retry-button:hover {
  background-color: #e74c3c;
}

/* 数据表格 */
.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th,
.data-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
}

.data-table tr:hover {
  background-color: #f5f5f5;
}

.table-row {
  transition: background-color 0.2s ease;
}

.table-row:hover {
  background-color: #f0f9ff;
}

/* 状态标签 */
.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-completed {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-cancelled {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.status-refunded {
  background-color: #f0f5ff;
  color: #1890ff;
}

.status-unknown {
  background-color: #f5f5f5;
  color: #999;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-button {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.view-button {
  background-color: #409eff;
  color: white;
}

.view-button:hover {
  background-color: #337ecc;
}

.view-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.view-button:disabled:hover {
  background-color: #ccc;
}

/* 空数据提示 */
.empty-data {
  text-align: center;
  padding: 40px;
  color: #999;
}

/* 分页 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
  padding: 20px;
}

.page-button {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.page-button:hover:not(:disabled) {
  border-color: #409eff;
  color: #409eff;
}

.page-button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.page-numbers {
  display: flex;
  gap: 5px;
}

.page-number {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.page-number:hover {
  border-color: #409eff;
  color: #409eff;
}

.page-number.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.page-number:disabled {
  background-color: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

.page-number:disabled:hover {
  border-color: #ddd;
  color: #ccc;
}

.page-info {
  margin-left: 20px;
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .registration-order-management {
    padding: 10px;
  }
  
  .filter-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-input {
    min-width: auto;
  }
  
  .status-tabs {
    flex-wrap: wrap;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .pagination {
    flex-wrap: wrap;
  }
}
</style>


